<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use addons\epay\library\Service;
use Exception;
use app\admin\model\personal\AccountLog;
use app\admin\model\finance\FinanceLog;

/**
 *  支付
 */
class Pay extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


	public function notifyx()
	{
		$paytype = $this->request->param('paytype');
		//添加分组，只有投诉咨询和一级客服可以分配
		$pay = Service::checkNotify($paytype);
		if (!$pay) {
			echo '签名错误';
			return;
		}
		$data = $pay->verify();
		try {
			$payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
			$type = $paytype == 'alipay' ? '支付宝' : '微信';
			$out_trade_no = $data['out_trade_no'];

			//你可以在此编写订单逻辑
			$recharge = Db::name('recharge')->where('log_sn',$out_trade_no)->find();
			$ret1 = [
				'uid'   =>  $recharge['uid'],
				'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
				'money' =>  '+'.$recharge['amount'],
				'type'  =>  3,
				'content'   =>  '充值',
				'createtime'    =>  time(),
				'arrivaltime'   =>  time(),
				'status'    =>  1
			];
			$re['s1'] = Db::name('personal')->where('id',$recharge['uid'])->setInc('balance',$recharge['amount']);
			$re['s2'] = Db::name('account_log')->insert($ret1);
			$re['s3'] = Db::name('recharge')->where('log_sn',$out_trade_no)->update(['status'=>1]);
		} catch (Exception $e) {
		}
		if ($paytype == 'alipay') {
			return 'success';
		} else {
			return 'SUCCESS';
		}
	}



    public function notifyre()
    {
        $paytype = $this->request->param('paytype');
        //添加分组，只有投诉咨询和一级客服可以分配
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $type = $paytype == 'alipay' ? '支付宝' : '微信';
            $out_trade_no = $data['out_trade_no'];

            //你可以在此编写订单逻辑
            $reorder = Db::name('reorder')->where('order_sn',$out_trade_no)->find();
            $user = Db::name('personal')->where('id',$reorder['buyid'])->value('switch');
            if ($user == 2) {
                $ret1 = [
                    'uid'   =>  $reorder['buyid'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '-'.$reorder['price'],
                    'type'  =>  1,
                    'content'   =>  '收货订单交易',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                $re['s1'] = Db::name('reorder')->where('order_sn',$out_trade_no)->update(['status'=>30,'paytime'=>time(),'payway'=>$type]);
                $re['s2'] = Db::name('account_log')->insert($ret1);
            } else {
                $ret1 = [
                    'uid'   =>  $reorder['buyid'],
                    'log_sn'    =>  date('YmdHis') . rand(10000000,99999999),
                    'money' =>  '-'.$reorder['price'],
                    'type'  =>  1,
                    'content'   =>  '收货订单交易',
                    'createtime'    =>  time(),
                    'arrivaltime'   =>  time(),
                    'status'    =>  1
                ];
                $re['s1'] = Db::name('reorder')->where('order_sn',$out_trade_no)->update(['status'=>2,'paytime'=>time(),'payway'=>$type]);
                $re['s2'] = Db::name('account_log')->insert($ret1);
                $send = new Send();
                if ($reorder['order_user'] == 1) {
                    $goods = Db::name('receiving')->where('id',$reorder['goods_id'])->find();
                    $re['s3'] = $send->send($goods['mobile'],6);
                } else {
                    $goods = Db::name('personal')->where('id',$reorder['uid'])->find();
                    $re['s4'] = $send->send($goods['mobile'],9);
                }
            }
        } catch (Exception $e) {
        }
        if ($paytype == 'alipay') {
            return 'success';
        } else {
            return 'SUCCESS';
        }
    }

    /*public function notify_wechat_refund()
    {
        error_log('notify_wechat_refund::::',3,'wechat_refund.log');
        $paytype = $this->request->param('paytype');
        // error_log($paytype,3,'wechat_refund.log');
        // $pay = Service::checkNotify($paytype);
        $pay = Service::checkNotify_refund($paytype);
        if($paytype == 'alipay'){
            error_log(json_encode($pay),3,'wechat_refund.log');
            if (!$pay) {
                error_log('1签名错误',3,'wechat_refund.log');
                echo '签名错误';
                return;
            }
            $data = $pay->verify($pay,true);
        }else{
            error_log('wechat_pay:::refund_data:'.json_encode($pay));
            $data = $pay;
        }
       
       
        try {
            error_log('000000',3,'wechat_refund.log');
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            // error_log(json_encode($data),3,'wechat_refund.log');
            
            $goods_info = DB::name("order")->where("order_sn",$out_trade_no)->find();
            error_log(date("Y-m-d H:i:s",time()).'查询订单'.$out_trade_no.':',3,'wechat_refund.log');
            if($goods_info){
                if($goods_info['status'] != 7){
                    DB::name("order")->where("order_sn",$out_trade_no)->update(['status'=>7]);
                }else{
                    die;
                }
                $uinfo = DB::name("personal")->where(['id'=>$goods_info['buyid']])->field('balance,jy_balance')->find();
                $log = new AccountLog();
                error_log('买家退款'.$goods_info['buyid'].':',3,'wechat_refund.log');
                $res = $log->addAccountLog($goods_info['buyid'], '+'.$goods_info['amount'], 5, '订单申请撤单退回', 1,'',1);
                if ($res !== false) {
                    Db::name('personal')->where(['id'=>$goods_info['buyid']])->setInc( 'balance', $goods_info['amount'] );
                }
                // dump($uinfo);
                $financelog = new FinanceLog();
                $financelog->addFinanceLog($goods_info['buyid'],'订单申请撤单退回',$uinfo['balance'],$uinfo['jy_balance'], $goods_info['amount'], $uinfo['balance']+$payamount,$uinfo['jy_balance'], $goods_info['reason']);
                error_log('写进财务log表'.$goods_info['buyid'].':',3,'wechat_refund.log');
            }
            
             $uinfo = DB::name("personal")->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
             $log = new AccountLog();
            $res = $log->addAccountLog($row['buyid'], '+'.$row['amount'], 5, '订单申请撤单退回', 1,'',1);
            if ($res !== false) {
                Db::name('personal')->where(['id'=>$row['buyid']])->setInc( 'balance', $row['amount'] );
            }
            $uinfo_after = $this->personal_model->where(['id'=>$row['buyid']])->field('balance,jy_balance')->find();
            // dump($uinfo);
            $financelog = new FinanceLog();
            $financelog->addFinanceLog($row['buyid'],'订单申请撤单退回',$uinfo['balance'],$uinfo['jy_balance'], $row['amount'], $uinfo_after['balance'],$uinfo_after['jy_balance'], $params['reason']);
            
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
        }
        if($paytype == 'wechat'){
            echo 'SUCCESS';
        }else{
            echo 'success';
        }
    }*/
    
    public function notify_wechat_refund()
    {
        // $pay = Service::checkNotify($paytype);
        $pay = Service::checkNotify_refund('wechat');
        error_log(json_encode($pay),3,'wechat_refund.log');
        if (!$pay) {
            error_log('1签名错误',3,'wechat_refund.log');
            echo '签名错误';
            return;
        }
        $data = $pay->verify(null,true);
       
        error_log('000000',3,'wechat_refund.log');
        try {
            error_log('0000001',3,'wechat_refund.log');
            $payamount = $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];
            // error_log(json_encode($data),3,'wechat_refund.log');
            
            $goods_info = DB::name("order")->where("order_sn",$out_trade_no)->find();
            error_log(date("Y-m-d H:i:s",time()).'查询订单'.$out_trade_no.':',3,'wechat_refund.log');
            if($goods_info){
                if($goods_info['status'] != 7){
                    DB::name("order")->where("order_sn",$out_trade_no)->update(['status'=>7]);
                }else{
                    echo 'SUCCESS';die;
                }
                $uinfo = DB::name("personal")->where(['id'=>$goods_info['buyid']])->field('balance,jy_balance')->find();
                $log = new AccountLog();
                error_log('买家退款'.$goods_info['buyid'].':',3,'wechat_refund.log');
                $res = $log->addAccountLog($goods_info['buyid'], '+'.$goods_info['amount'], 5, '客服后台退款', 1,'',1);
            }
            
            //你可以在此编写订单逻辑
        } catch (Exception $e) {
        }
        if($paytype == 'wechat'){
            echo 'SUCCESS';
        }else{
            echo 'success';
        }
    }


}
